package com.qunar.toku.handler;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;

import com.qunar.toku.proxy.RequestProtocol;

/**
 * 抽象父类
 * 
 * @author zhangwan
 * @email wan.zhang@qunar.com
 */
public abstract class ChannelServerHandler extends SimpleChannelUpstreamHandler {
	private final InternalLogger logger = 
			InternalLoggerFactory.getInstance(ChannelServerHandler.class);
	
	protected abstract void execute(Channel channel, Object message);

	@Override
	public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		logger.info("client address connected>>>:" + ctx.getChannel().getRemoteAddress());
	}

	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		logger.info("client address closed<<<:" + ctx.getChannel().getRemoteAddress());
	}

	/**
	 * ChannelHandlerContext ctx, MessageEvent e 都可以获得一个Channel
	 * 他们没什么区别,都是指向同一个Channel
	 */
	@Override
	public final void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		RequestProtocol protocol = (RequestProtocol) e.getMessage();
		logger.info("invoke:" + protocol);
		execute(ctx.getChannel(), protocol);
	}
	
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		logger.error("exception:" + e.getCause());
		ctx.getChannel().close();
	}

}
